package com.itheima.sh.controller;

import com.itheima.sh.pojo.User;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;


@RestController
@RequestMapping("consumer")

public class ConsumerController {

    @Autowired
    RestTemplate restTemplate;

    @Autowired
    DiscoveryClient discoveryClient;

    @GetMapping("{id}")
    @HystrixCommand(fallbackMethod = "findUserFallBack")
    public User findUser(@PathVariable("id") String username){
        //String url = "http://localhost:8081/user/" + id;
//        List<ServiceInstance> instances = discoveryClient.getInstances("user-service");
//        ServiceInstance serviceInstance = instances.get(0);
//        //第一种方案
//        String host = serviceInstance.getHost(); //IP
//        int port = serviceInstance.getPort(); //port

        //第二种方案
//        String uri = serviceInstance.getUri().toString();
//        String url = "http://"+uri+"/user/" + username;
        // 调用RestTemplate的getForObject方法，指定url地址和返回值类型
        String url = "http://user-service/user/" + username;
        User user = restTemplate.getForObject(url, User.class);
        return user;
    }

    //备选方案，符合预期，可处理的返回值
    public User findUserFallBack(String username){
        User user = new User();
        user.setEmail("-1");
        user.setUsername(username);
        user.setName("暂停服务");
        return user;
    }
}
